<template>
  <div>
    <el-form :model="form" label-width="80px">
      <el-form-item label="图书名称">
        <el-input v-model="form.title" placeholder="图书名称" />
      </el-form-item>
      <el-form-item label="图书说明">
        <el-input v-model="form.description" placeholder="图书说明" />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          v-text="'保存'"
          @clink="submit"  />
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { Book } from '../../api/type'
import { getBookById, postBook } from '../../api/index'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

// 获取路由参数和路由实例
const $route = useRoute()
const $router = useRouter()
// 存放 _id 如果没有则为 undefined 或 null
const _id = ref(String($route.query._id))
console.log(_id.value)

// 初始化表单数据
const form: Book = reactive({
  _id: _id.value,
  title: '',
  description: ''
})
// 重置表单数据
const reset = () => {
  form._id = ''
  form.title = ''
  form.description = ''
}

// 提交按钮
const submit = () => {
  // 提交数据接口
  postBook(form).then((res) => {
    ElMessage.success(res.message)
  }).finally(() => {
    // 无论接口状态如何 finally 下的回调总会执行
    reset()
    $router.push('/bookList')
  })
}

// 是否接收到列表页传入的 _id
if(_id.value !== undefined || _id.value !== null) {
  // 根据图书 _id 获取图书数据
  getBookById(_id.value).then((res) => {
    // 成功后将数据存放到表单的输入框中
    form.title = res.data.title
    form.description = res.data.description
  }).catch((e) => {
    console.log(e)
  })
} else {
  reset()
}
</script>
<style lang="">
  
</style>